package nettyTest.netty4test1.byteBuf;

import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import org.junit.Test;

/**
 * @author yangxp
 * 2020年4月8日下午4:39:15
 * <p>描述：
 * PooledHeapByteBuf ：池化的堆内缓冲区；
 * PooledUnsafeHeapByteBuf ：池化的 Unsafe 堆内缓冲区；
 * PooledDirectByteBuf ：池化的直接(堆外)缓冲区；
 * PooledUnsafeDirectByteBuf ：池化的 Unsafe 直接(堆外)缓冲区；
 * UnpooledHeapByteBuf ：非池化的堆内缓冲区；
 * UnpooledUnsafeHeapByteBuf ：非池化的 Unsafe 堆内缓冲区；
 * UnpooledDirectByteBuf ：非池化的直接(堆外)缓冲区；
 * UnpooledUnsafeDirectByteBuf ：非池化的 Unsafe 直接(堆外)缓冲区；
 */
public class ByteBufCreate {

    @Test
    public void byteBufCreate(){
        // 分别用来分配池化的和未池化的ByteBuf
        ByteBuf buf1 = Unpooled.buffer();
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);

        byte[] byte1 = new byte[]{1, 2, 3, 4, 5};
        ByteBuf buf2 = Unpooled.wrappedBuffer(byte1); // UnpooledHeapByteBuf

        int n = 'A' + '6' - '3';
        System.out.println(n);
        System.out.println((2 << 14) * 1000);

        // 8 种ByteBuf 的实践
        ByteBuf byteBuf1 = PooledByteBufAllocator.DEFAULT.heapBuffer(2 << 6); //128 PooledHeapByteBuf
        ByteBuf byteBuf2 = PooledByteBufAllocator.DEFAULT.heapBuffer(2 << 7); //256
        ByteBuf byteBuf3 = PooledByteBufAllocator.DEFAULT.heapBuffer(2 << 8); // 512
        ByteBuf byteBuf4 = PooledByteBufAllocator.DEFAULT.heapBuffer(2 << 9); // 1024
        ByteBuf byteBuf5 = PooledByteBufAllocator.DEFAULT.heapBuffer(2 << 10); //2048
        ByteBuf byteBuf6 = PooledByteBufAllocator.DEFAULT.heapBuffer(2 << 13); //16384
        ByteBuf byteBuf7 = PooledByteBufAllocator.DEFAULT.heapBuffer(2 << 14); //32768
        ByteBuf byteBuf8 = PooledByteBufAllocator.DEFAULT.heapBuffer((2 << 14) * 1000); //32768000

//		PooledByteBufAllocator.DEFAULT.directBuffer();// PooledDirectByteBuf
//		ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.heapBuffer();// UnpooledHeapByteBuf
//		UnpooledByteBufAllocator.DEFAULT.directBuffer();
    }

    public static void printByteBuf(ByteBuf buf) {
        if (buf.hasArray()) {
            System.out.println("buffer3 array: " + buf.array());
            System.out.println("Buffer3 array offset: " + buf.arrayOffset());
        }
        System.out.println("Capacity: " + buf.capacity());
//		System.out.println("Limit: " + buf.);
//		System.out.println("Position: " + buf.position());
//		System.out.println("Remaining: " + buf.remaining());
    }
}
